<template>
    <div class="editable" v-loading="settingrank"
         element-loading-text="权限设置中请稍后">
        <div class="el-table-top clearfix">
            <div class="el-table-top-left">
                <i class="fa fa-plus fa-2x" title="新建记录" @click="dealWithRecord()"></i>
                <i class="fa fa-refresh fa-2x" :class="refreshHover?'':'fa-spin'" title="刷新" @click="refresh()"
                   @mouseenter="refreshHover=!refreshHover" @mouseleave="refreshHover=!refreshHover"></i>
            </div>

            <el-radio-group v-model="sys" @change="chooseSys()">
                <el-radio :label="'hc-sales'">hc-sales</el-radio>
                <el-radio :label="'hc-crm'">hc-crm</el-radio>
            </el-radio-group>
        </div>


        <!--<div class="row-table">-->
        <!--<div class="row row-title">-->
        <!--<div class="col-xs-4">登录ID</div>-->
        <!--<div class="col-xs-4">用户名</div>-->
        <!--<div class="col-xs-4">店铺</div>-->
        <!--</div>-->
        <!--<div class="row row-tr">-->
        <!--<div class="col-xs-4">HYKD03</div>-->
        <!--<div class="col-xs-4">龚秋菊</div>-->
        <!--<div class="col-xs-4">华洋</div>-->
        <!--</div>-->

        <!--</div>-->


        <el-table
                ref="userTable"
                :data="tableData"
                highlight-current-row
                @current-change="handleCurrentChange"
                style="width: 100%"
                :row-key="getRowKeys"
                :expand-row-keys="expands"
                :default-sort="{prop: 'name', order: 'descending'}"
        >
            <!--@expand="getOneExpand"-->
            <!--<el-table-column type="expand">-->
            <!--<template scope="props">-->
            <!--<el-form label-position="left" inline class="demo-table-expand">-->
            <!--&lt;!&ndash;<el-form-item label="ID">&ndash;&gt;-->
            <!--&lt;!&ndash;<el-input v-model="props.row.id" placeholder="请输入ID" class="uuid" :disabled="true"></el-input>&ndash;&gt;-->
            <!--&lt;!&ndash;</el-form-item>&ndash;&gt;-->

            <!--<el-form-item label="登录 ID">-->
            <!--<el-input v-model="props.row.uid" placeholder="请输入登录ID" :disabled="true"></el-input>-->
            <!--</el-form-item>-->
            <!--<el-form-item label="用户名">-->
            <!--<el-input v-model="props.row.name" placeholder="请输入用户名"></el-input>-->
            <!--</el-form-item>-->

            <!--<el-form-item label="用户密码">-->
            <!--<el-input v-model="props.row.password" placeholder="请输入用户密码"></el-input>-->
            <!--</el-form-item>-->

            <!--<el-form-item label="邮箱">-->
            <!--<el-input v-model="props.row.email" placeholder="请输入email"></el-input>-->
            <!--</el-form-item>-->

            <!--<el-form-item label="性别">-->
            <!--<el-radio-group v-model="props.row.sex">-->
            <!--<el-radio :label="0">男</el-radio>-->
            <!--<el-radio :label="1">女</el-radio>-->
            <!--</el-radio-group>-->
            <!--</el-form-item>-->

            <!--<el-form-item label="店铺 ID">-->
            <!--<el-select v-model="props.row.shop_id" placeholder="请选择">-->
            <!--<el-option-->
            <!--v-for="item in shops"-->
            <!--:label="item.name"-->
            <!--:value="item.id">-->
            <!--</el-option>-->
            <!--</el-select>-->
            <!--</el-form-item>-->

            <!--<el-form-item label="电话号码">-->
            <!--<el-input v-model="props.row.tel" placeholder="请输入电话号码"></el-input>-->
            <!--</el-form-item>-->

            <!--<el-form-item>-->
            <!--<div class="man">-->
            <!--<i class="fa fa-save" title="保存" @click="editConfirm(props.row)"></i>-->
            <!--<i class="fa fa-trash" title="删除" @click="removeConfirm(props.row)"></i>-->
            <!--</div>-->
            <!--</el-form-item>-->

            <!--</el-form>-->
            <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column
                    label="登录 ID"
                    prop="uid" sortable>
            </el-table-column>
            <el-table-column
                    label="用户名"
                    prop="name" sortable :sort-method="pinyinSort">
            </el-table-column>
            <el-table-column
                    label="店铺"
                    prop="shop_name"
                    :formatter="formatter">
            </el-table-column>


            <el-table-column
                    label="操作"
                    width="120">
                <template scope="scope">
                    <el-dropdown>
                            <span class="el-dropdown-link">
                                <i class="el-icon-caret-bottom el-icon--right" style="cursor: pointer"></i>
                            </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native.prevent="setPrivilege(scope.$index, scope.row)">
                                设置权限
                            </el-dropdown-item>

                            <el-dropdown-item @click.native.prevent="deleteRow(scope.$index, scope.row)">
                                移除
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>


                </template>
            </el-table-column>
        </el-table>


        <div class="row-content" v-show="showDialog">
            <div class="el-dialog el-dialog--large">
                <div class="el-dialog__header">
                    <span class="el-dialog__title">用户信息</span>
                    <div class="el-dialog__headerbtn">
                        <i class="el-dialog__close el-icon el-icon-close" @click="closeDialog()"></i>
                    </div>
                </div>
                <div class="el-dialog__body">
                    <div class="row sync-info">
                        <div class="col-xs-6">
                            <div class="col-xs-3 tips">登录ID:</div>
                            <div class="col-xs-9">
                                <div class="el-input">
                                    <!----><!---->
                                    <input type="text" v-model="fields.uid" placeholder="请输入登录ID" autocomplete="off"
                                           class="el-input__inner">
                                    <!----><!---->
                                </div>
                            </div>
                        </div>
                        <div class="col-xs-6">
                            <div class="col-xs-3 tips">用户:</div>
                            <div class="col-xs-9">
                                <div class="el-input">
                                    <!----><!---->
                                    <input type="text" v-model="fields.name" placeholder="请输入用户名字"
                                           autocomplete="off" class="el-input__inner">
                                    <!----><!----></div>
                            </div>
                        </div>
                    </div>
                    <div class="row sync-info">
                        <div class="col-xs-6">
                            <div class="col-xs-3 tips">
                                密码:
                            </div>
                            <div class="col-xs-9">
                                <div class="el-input"><!----><!----><input type="text" v-model="fields.password"
                                                                           placeholder="请输入密码" autocomplete="off"
                                                                           class="el-input__inner"><!----><!----></div>
                            </div>
                        </div>
                        <div class="col-xs-6">
                            <div class="col-xs-3 tips">
                                电话:
                            </div>
                            <div class="col-xs-9">
                                <div class="el-input"><!----><!----><input type="text" v-model="fields.tel"
                                                                           placeholder="请输入电话" autocomplete="off"
                                                                           class="el-input__inner"><!----><!----></div>
                            </div>
                        </div>
                    </div>
                    <div class="row sync-info">
                        <div class="col-xs-6">
                            <div class="col-xs-3 tips">
                                邮箱:
                            </div>
                            <div class="col-xs-9">
                                <div class="el-input"><!----><!----><input type="text" v-model="fields.email"
                                                                           placeholder="请输入邮箱" autocomplete="off"
                                                                           class="el-input__inner"><!----><!----></div>
                            </div>
                        </div>
                        <div class="col-xs-6">
                            <div class="col-xs-3 tips">
                                性别:
                            </div>
                            <div class="col-xs-9">
                                <el-radio-group v-model="fields.sex" style="height: 34px;line-height: 34px;">
                                    <el-radio :label="0">男</el-radio>
                                    <el-radio :label="1">女</el-radio>
                                </el-radio-group>
                            </div>
                        </div>
                    </div>
                    <div class="row sync-info">
                        <div class="col-xs-6">
                            <div class="col-xs-3 tips">
                                门店:
                            </div>
                            <div class="col-xs-9">
                                <el-select v-model="fields.shop_id" placeholder="请选择">
                                    <el-option
                                            v-for="item in shops"
                                            :label="item.name"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                        </div>
                    </div>
                    <div class="row" style="margin-bottom: 10px">
                        <div class="col-xs-6" style="text-align: center;height:34px;line-height:34px;">
                            <i class="el-icon-arrow-down arrows" v-show="!showShop" @click="showShops()"></i>
                            <i class="el-icon-arrow-up arrows" v-show="showShop" @click="hideShops()"></i>
                            <span>(点击选择可视门店)</span>
                        </div>
                        <div class="col-xs-3"></div>
                        <div class="col-xs-3" style="text-align: right; padding-right: 30px;">
                            <button class="btn btn-primary" v-show="!isEdit" @click="addConfirm(fields)">新增</button>
                            <button class="btn btn-primary" v-show="isEdit" @click="editConfirm(fields)">修改</button>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xs-9" style="margin-left: 15px">
                            <el-transfer v-model="selectedViewShops"
                                         :data="viewShopsData"
                                         :titles="['可选门店','已选门店']"
                                         @change="handleChange"
                                         v-show="showShop"></el-transfer>
                        </div>
                        <div class="col-xs-3"></div>
                    </div>
                </div>

            </div>
        </div>


        <el-dialog title="设置权限" :visible.sync="dialogTableVisible" :close-on-click-modal="false" :size="'large'">

            <div class="row ranktransfer">
                    <!--<div class="el-loading-spinner">-->
                        <!--<svg viewBox="25 25 50 50" class="circular">-->
                            <!--<circle cx="50" cy="50" r="20" fill="none" class="path"></circle>-->
                        <!--</svg>-->
                    <!--</div>-->
                <div class="col-xs-7 col-xs-offset-1">
                    <el-transfer v-loading="settingrank"
                                 element-loading-text="拼命加载中"
                            filterable
                            filter-placeholder="请输入岗位"
                            v-model="ownrankids"
                            :props="{
                              key: 'id',
                              label: 'name'
                            }"
                            :data="ranks"
                            @change="changeRanks"
                            :titles="['未分配的岗位', '已有岗位']">
                    </el-transfer>
                </div>

                <div class="col-xs-4">
                    <div class="row" style="background: #232323;height: 35px;line-height: 35px;padding-left: 12px;color: white;">
                        角色:
                    </div>
                    <div class="row-roles" style="height: 600px;overflow: scroll;">
                        <div v-for="role in roles" style="height: 30px;line-height: 30px;font-weight: 500;">
                            {{role.rolename}}
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<style lang="less">
    .editable {
        position: relative;
        margin-bottom: 310px;
    }

    .sync-info {
        margin-bottom: 20px;
    }

    .demo-table-expand {
        font-size: 0;
    }

    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }

    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }

    .el-form-item__content .uuid {
        width: 180%;
    }

    .row-title {
        font-size: 14px;
        font-weight: 600;
        text-align: center;
        height: 50px;
        line-height: 50px;
        background: #EEF1F6;
        margin: 0;
    }

    .row-tr {
        font-size: 14px;
        text-align: center;
        height: 40px;
        line-height: 40px;
        background: #FFFFFF;
        margin: 0;

        &:hover {
            cursor: pointer;
            background: #0B9EFF;
        }
    }

    .row-content {
        position: fixed;
        height: 360px;
        bottom: 0;
        left: 290px;
        right: 40px;
        background: #ECECEC;
        z-index: 5;

        .el-dialog--large {
            width: 100%
        }

    }

    .man {
        width: 250px;
        overflow: auto;
        zoom: 1;
        clear: both;
        font-size: 30px;
    }

    .fa-save {
        float: left;
    }

    .fa-save:hover {
        color: orange;
        cursor: pointer;
    }

    .fa-trash {
        float: right;
    }

    .fa-trash:hover {
        color: orange;
        cursor: pointer;
    }

    .arrows:hover {
        cursor: pointer;
        color: #3BAAFE;
    }
    .ranktransfer .el-transfer-panel__body {
        height: 500px;
    }
    .ranktransfer .el-checkbox-group.el-transfer-panel__list.is-filterable {
        height: 450px;
    }
</style>

<script>
    import {API_ROOT} from '../../config'
    import _ from 'lodash'
    var pinyin = require('pinyin')
    import moment from 'moment'

    export default {
        data() {

//            const generateData2 = _ => {
//                const data = [];
//                const cities = ['上海', '北京', '广州', '深圳', '南京', '西安', '成都'];
//                const pinyin = ['shanghai', 'beijing', 'guangzhou', 'shenzhen', 'nanjing', 'xian', 'chengdu'];
//                cities.forEach((city, index) => {
//                    data.push({
//                        label: city,
//                        key: index,
//                        pinyin: pinyin[index]
//                    });
//                });
//                return data;
//            };

            return {

//                data2: generateData2(),
                ownranks: [],
                ownrankids: [],
                currentPrivilegedUserId: '',

                dialogTableVisible: false,

                ranks: [],

                roles: [],

                settingrank: false,

                selectedValues: [],

                selectedViewShops: [],


                view_shops: '',

                expands: [],

                sys: 'hc-crm',

                paging: {
                    total: 0,
                    limit: 10,
                    offset: 0
                },

                fields: {
                    name: "",
                    password: "",
                    rank: "",
                    sex: 1,
                    shop_id: "",
                    tel: "",
                    uid: "",
                    email: ""
                },
                field: {
                    id: "005f9c2db58b4d0186235c0ee84d9a93",
                    name: "陆燕",
                    password: "123456",
                    rank: "",
                    sex: 1,
                    shop_id: "a58f764a950b46c580ad91cc34e325e9",
                    tel: "15106205583",
                    uid: "HHBK25",
                    _roles: {},
                    _shop: {
                        brands: "''",
                        id: "195e9d4e0ad440d7bded3ed27f4fd0c6",
                        name: "保险代理公司",
                        seq: -2,
                        type: 0
                    }
                },

                currentRow: {
                    uid: "",
                    name: "",
                    password: "",
                    tel: "",
                    email: "",
                    sex: 0,
                    shop_id: ""
                },

                refreshHover: false,

                searchString: '',

//                currentPage: 1,

                tableData: [],

                shops: [],

                showShop: false,

                selectedShops: [],

                all_view_shops: [],

                showDialog: false,

                isEdit: false
            }
        },
        methods: {
            resetFields(fields) {
                if (!fields) {
                    this.fields = {
                        name: "",
                        password: "",
                        rank: "",
                        sex: 1,
                        shop_id: "",
                        tel: "",
                        uid: "",
                        email: "",
                    }
                } else {
                    this.fields = fields
                }
                this.showDialog = true;
            },

            closeDialog() {
                this.showDialog = false;
            },
            searchTable() {

                if (this.selectedValues.length == 0) {
                    this.searchString = ''
                }
                console.log('confirm searching', this.searchString, this.selectedValues, 'haha')
                const that = this;
                var instance = this.$http.create(
                        {
                            headers: {
                                'socket-id': that.$socket.id,
                                'auth': JSON.parse(localStorage.getItem(that.sys)).authorize
                            }
                        }
                );

                var params = {};

                that.selectedValues.forEach(function (item, index) {
                    params[item] = that.searchString;
                })

                params['offset'] = that.paging.offset;
                params['limit'] = that.paging.limit;

                instance.get(API_ROOT + '/user', {
                    params: params
                }).then(function (dt) {
                    if (dt.data.status.code == 0) {

                        if (dt.data.data.rows == '403001') {
                            console.log('55955959599')
                            return that.$router.push('/login');
                        }

                        console.log(dt.data.data.rows, 'tttttt5');

                        for (var i = 0; i < dt.data.data.rows.length; i++) {
                            console.log(dt.data.data.rows[i]);
                        }
                        that.paging.total = dt.data.data.count;
                        if (dt.data.data.count == 0) {
                            that.$message({
                                type: 'success',
                                message: '相应记录为0条'
                            })
                        }
                    } else {
                        that.$message({
                            type: 'warning',
                            message: '查询出错,查询格式不对'
                        })
                    }
                })
            },
            chooseSys() {
                const that = this;
                if (JSON.parse(localStorage.getItem(that.sys)).status != 0) {
                    return that.$router.push('/choosesys');
                }
                this.getData();
            },
            setCurrent(row) {
                this.$refs.userTable.setCurrentRow(row)
            },
            getData() {
                const that = this;
                that.getShops();
                if (JSON.parse(localStorage.getItem(that.sys)).status != 0) {
                    return that.$message({
                        type: 'error',
                        message: that.sys + '系统登录验证出错'
                    })
                }
                that.tableData = [];
                that.paging.total = 0;

                var instance = this.$http.create(
                        {
                            headers: {
                                'socket-id': that.$socket.id,
                                'auth': JSON.parse(localStorage.getItem(that.sys)).authorize
                            }
                        }
                );
                instance.get(API_ROOT + '/api/users', {
                    params: {
                        url: JSON.parse(localStorage.getItem(that.sys)).url,
                        sys: that.sys,
                        offset: that.paging.offset,
                        limit: that.paging.limit
                    }
                }).then(function (dt) {
                    if (dt.data.status.code == 0) {

                        if (dt.data.data.rows.code && dt.data.data.rows.code == '403001') {
                            return that.$router.push('/login');
                        }

                        console.log(dt.data.data.rows, ' - -- -  -- - this is data rows!');
                        that.tableData = dt.data.data.rows;
                        that.resetFields();
                        that.expands.push(that.tableData[0].id);
                        that.paging.total = dt.data.data.count;
                    }
//                    else {
//                        return that.$router.push('/login');
//                    }
                });
            },
            getShops() {
                const that = this;
                if (JSON.parse(localStorage.getItem(that.sys)) && JSON.parse(localStorage.getItem(that.sys)).authorize) {
                    var instance = this.$http.create({
                        headers: {
                            'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                            'socket-id': that.$socket.id
                        }
                    });
                    instance.get(API_ROOT + '/api/shops', {
                        params: {
                            url: JSON.parse(localStorage.getItem(that.sys)).url,
                            sys: that.sys
                        }
                    }).then(function (dt) {
                        if (dt.data.status.code == 0) {
                            that.shops = dt.data.data.rows;
                            try {
                                that.all_view_shops = that.shops.map(function (i) {
                                    return i.name
                                });
                            } catch (e) {
                                that.$router.push('/login');
                            }
                            console.log('get api shop success!');
                        }
                    })
                } else {
                    return that.$router.push('/login');
                }
            },

            showShops() {
                this.showShop = true;
                $('.row-content').animate({height: '650px'});
            },
            hideShops() {
                this.showShop = false;
                $('.row-content').animate({height: '360px'});
            },

            refresh() {
                const that = this;
                this.$message({
                    type: 'success',
                    message: '刷新成功!'
                })
                that.isEdit = false;
                that.getData();
            },
            dealWithRecord(scope) {
                const that = this;
                that.showDialog = true;
                if (scope) {
                    that.resetFields(scope.row)
                    that.isEdit = true;
                } else {
                    that.resetFields();
                    that.isEdit = false;
                }
            },

            editRow(fields) {
                const that = this;
                console.log(fields, ' this is scope')

                var filtedShop = that.shops.filter(function (item) {
                    return item.id == fields.shop_id;
                })
                fields._shop = filtedShop[0];
                var instance = this.$http.create(
                        {
                            headers: {
                                'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                                'socket-id': that.$socket.id
                            }
                        }
                );
                return instance.put(API_ROOT + '/api/users/' + fields.uid, {
                    dt: fields,
                    sys: that.sys,
                    url: JSON.parse(localStorage.getItem(that.sys)).url
                });
            },

            editConfirm(fields) {
                const that = this;
                that.editRow(fields).then(function (dt) {
                    console.log(dt, 'this is dddddt')
                    if (dt.data.status.code == 0) {
                        that.$message({
                            type: 'success',
                            message: '修改成功!'
                        })
                    } else {
                        that.$message({
                            type: 'error',
                            message: '修改失败!'
                        })
                    }
                });
            },
            addRow(fields) {
                const that = this;
                var instance = this.$http.create(
                        {
                            headers: {
                                'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                                'socket-id': that.$socket.id,
                            }
                        }
                );
                return instance.post(API_ROOT + '/api/users', {
                    dt: fields,
                    sys: that.sys,
                    url: JSON.parse(localStorage.getItem(that.sys)).url
                });
            },


            addConfirm(fields) {
                const that = this;
                console.log('confirm add')
                for (var i in fields) {
                    console.log(i, '---- --  -- - - - -', fields[i])
                    if (!fields[i] && fields != 0) delete fields[i];
                }

                console.log('fields -  - - - - - ', fields)
                that.addRow(fields).then(function (dt) {
                    if (dt.data.status.code == 0) {
                        console.log('添加成功!')
                        that.showDialog = false;
                        that.refresh();
                        that.resetFields();
                    } else {
                        console.log('新建失败!')
                        that.$message({
                            type: 'error',
                            message: dt.data.data.err
                        })
                    }
                });
            },

            removeRow(fields) {
                const that = this;
                var instance = this.$http.create(
                        {
                            headers: {
                                'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                                'socket-id': that.$socket.id
                            }
                        }
                );
                return instance.delete(API_ROOT + '/api/users/' + fields.uid, {
                    data: {
                        url: JSON.parse(localStorage.getItem(that.sys)).url,
                        sys: that.sys
                    }
                })
            },
            removeConfirm(fields) {
                const that = this;
                that.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    that.removeRow(fields).then(function (dt) {
                        console.log('this is removedt', dt);
                        if (dt.data.status.code == 0) {
                            console.log('删除成功!');
                            that.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            that.refresh();
                        } else if (dt.data.data.err) {
                            that.$message({
                                type: 'error',
                                message: '删除失败!' + dt.data.data.err
                            });
                        } else {
                            that.$message({
                                type: 'error',
                                message: '删除失败!'
                            });
                        }
                    })
                }).catch((e) => {
                    console.log(e)
                    that.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            deleteRow(index, row) {
                console.log('deleteRow! this is deleteRow!!!', index, row)
                this.removeConfirm(row);
            },

            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.paging.limit = val;
                this.getData()
            },
            handleCurrentChange(val) {
                if (val) {
                    const that = this;
                    that.showDialog = true;
                    that.isEdit = true;
                    var instance = this.$http.create(
                            {
                                headers: {
                                    'socket-id': that.$socket.id,
                                    'auth': JSON.parse(localStorage.getItem(that.sys)).authorize
                                }
                            }
                    );

                    instance.get(API_ROOT + '/api/users/' + val.uid, {
                        params: {
                            url: JSON.parse(localStorage.getItem(that.sys)).url,
                            sys: that.sys
                        }
                    }).then(function (dt) {
                        if (dt.data.status && dt.data.status.code == 0) {
                            if (dt.data.data.row.code == 403001) {
                                return that.$router.push('/login');
                            }
                            that.fields = dt.data.data.row;
                            that.view_shops = dt.data.data.row._view_shops;
                            console.log('lalalal', that.view_shops);
                            that.fields.sex = parseInt(that.fields.sex);

                            that.selectViewShops();
                        }
                    });
                }
            },
            handleChange(value, direction, movedKeys) {
                const that = this;
                const arr = [];
                for (let i = 1; i <= that.viewShopsData.length; i++) {
                    if (value.indexOf(that.viewShopsData[i - 1].key) >= 0) {
                        console.log(value, that.viewShopsData[i - 1].key, that.viewShopsData[i - 1].label, ' = -   -- - -');
                        arr.push(that.viewShopsData[i - 1].label)
                    }
                }

                that.fields._view_shops = arr.join(",");
                console.log(that.fields)
            },
            formatedDate(date) {
                if (date) {
                    return moment(date).format('YYYY-MM-DD HH:mm:ss')
                }
            },
            getRowKeys(row) {
                return row.id;
            },
            formatter(row, column) {
                var vm = this;
                var filterd = vm.shops.filter(function (i) {
                    return i.id == row.shop_id
                });
                if (filterd[0]) {
                    return filterd[0]['name'];
                } else {
                    return ''
                }
            },

            getOneExpand(row, expanded) {
                if (expanded) {
                    const that = this;
                    console.log(row, expanded, '|||||||| -- ||||||||')


                    var instance = this.$http.create(
                            {
                                headers: {
                                    'socket-id': that.$socket.id,
                                    'auth': JSON.parse(localStorage.getItem(that.sys)).authorize
                                }
                            }
                    );

                    instance.get(API_ROOT + '/api/users/' + row.uid, {
                        params: {
                            url: JSON.parse(localStorage.getItem(that.sys)).url,
                            sys: that.sys
                        }
                    }).then(function (dt) {

                        if (dt.data.status && dt.data.status.code == 0) {
                            row = dt.data.data.row
                        }
                    });
                }
            },

            selectViewShops() {
                const that = this;
                const data = [];
                var viewShopString = that.view_shops + '';
                console.log(viewShopString, 'this is view shop string!!!')

                for (let i = 1; i <= that.viewShopsData.length; i++) {
                    if (viewShopString.indexOf(that.viewShopsData[i - 1].label) >= 0) {
                        data.push(that.viewShopsData[i - 1].key);
                    }
                }
                console.log(data, 'this is sisisisisisisiisisissisidata')
                that.selectedViewShops = data;
            },

            pinyinSort(a, b) {
//                if(a['name']&&b['name']) {
//                    return a['name'].pinyin.localeCompare(b['name'].pinyin)
//                }else {
//                    return 1
//                }
//                return 1
                return pinyin(a['name']) > pinyin(b['name']);
            },

            setPrivilege(index, row) {
                const that = this;
                console.log('setting roles ', index, row)
                this.dialogTableVisible = true;
                this.currentPrivilegedUserId = row.id;

                this.getRoles(index, row).then(function(dt) {
                    if(dt.data.status.code == 0) {
                        that.roles = dt.data.data.rows;
                    }else {
                        that.$message({
                            type: 'error',
                            message: '获取角色出错'
                        })
                    }
                });

                this.getUserRank(index, row).then(function(dt) {
                    if(dt.data.status.code == 0) {
                        that.ownranks = dt.data.data.rows;
                        that.ownrankids = that.ownranks.map(function(rank) {
                            return rank.id;
                        });
                    }else {
                        that.$message({
                            type: 'error',
                            message: '获取权限出错'
                        })
                    }

                })
            },

            getRanks() {
                const that = this;

                if (JSON.parse(localStorage.getItem(that.sys)) && JSON.parse(localStorage.getItem(that.sys)).authorize) {
                    var instance = this.$http.create({
                        headers: {
                            'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                            'socket-id': that.$socket.id
                        }
                    });
                    instance.get(API_ROOT + '/api/ranks/', {
                        params: {
                            url: JSON.parse(localStorage.getItem(that.sys)).url,
                            sys: that.sys
                        }
                    }).then(function (dt) {
                        if (dt.data.status.code == 0) {
                            that.ranks = _.sortBy(dt.data.data.rows, ['name']);
                            that.ranks.forEach(function (item, i) {

                            })
                            console.log(that.ranks, 'this is ranks!!!')
                        } else {
                            that.$message({
                                type: 'error',
                                message: '获取权限出错'
                            })
                        }
                    });
                } else {
                    return that.$router.push('/login');
                }
            },

            getUserRank(index, row) {
                const that = this;
                var instance = this.$http.create({
                    headers: {
                        'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                        'socket-id': that.$socket.id
                    }
                });
                return instance.get(API_ROOT + '/api/users/' + row.id + '/ranks/', {
                    params: {
                        url: JSON.parse(localStorage.getItem(that.sys)).url,
                        sys: that.sys
                    }
                })
            },

            setRank(userid, rankid) {
                const that = this;
                var instance = this.$http.create({
                    headers: {
                        'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                        'socket-id': that.$socket.id
                    }
                });
                return instance.post(API_ROOT + '/api/users/' + userid + '/ranks/' + rankid, {
                        url: JSON.parse(localStorage.getItem(that.sys)).url,
                        sys: that.sys
                })
            },

            unsetRank(userid, rankid) {
                const that = this;
                var instance = this.$http.create({
                    headers: {
                        'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                        'socket-id': that.$socket.id
                    }
                });
                return instance.delete(API_ROOT + '/api/users/' + userid + '/ranks/' + rankid, {
                    data: {
                        url: JSON.parse(localStorage.getItem(that.sys)).url,
                        sys: that.sys
                    }
                })
            },

            changeRanks(value, direction, movedKeys) {
                console.log(value, direction, movedKeys)
                const that = this;
                that.settingrank = true;
                var rankChanges = [];
                if(direction== 'right') {
                    console.log('adding ranks');
                    for(var i =0; i< movedKeys.length; i++) {
                        rankChanges.push(that.setRank(that.currentPrivilegedUserId, movedKeys[i]));
                    }
                }else if(direction == 'left') {
                    console.log('removing ranks');
                    for(var i =0; i< movedKeys.length; i++) {
                        rankChanges.push(that.unsetRank(that.currentPrivilegedUserId, movedKeys[i]));
                    }
                }

                Promise.all(rankChanges).then(function(dt) {
                    that.getRoles(undefined, {id: that.currentPrivilegedUserId}).then(function(dt) {
                        if(dt.data.status.code == 0) {
                            that.roles = [];
                            console.log(dt.data.data.rows, 'roles  - - -- - -')
                            that.roles = dt.data.data.rows;
                        }else {
                            that.$message({
                                type: 'error',
                                message: '获取角色出错'
                            })
                        }
                    });
                    that.settingrank = false;
                });
            },

            getRoles(index, row) {
                const that = this;
                var instance = this.$http.create({
                    headers: {
                        'auth': JSON.parse(localStorage.getItem(that.sys)).authorize,
                        'socket-id': that.$socket.id
                    }
                });
                return instance.get(API_ROOT + '/api/rbac/users/' + row.id + '/roles/', {
                    params: {
                        url: JSON.parse(localStorage.getItem(that.sys)).url,
                        sys: that.sys
                    }
                })
            }
        },
        created() {
            this.getData();
            this.getRanks();
        },
        computed: {
            selectedOptions() {
                var arr = [];
                for (var i in this.titleMaps) {
                    arr.push({
                        label: this.titleMaps[i],
                        value: i
                    })
                }
                return arr;
            },

            viewShopsData() {
                const data = [];
                for (let i = 1; i <= this.all_view_shops.length; i++) {
                    data.push({
                        key: i,
                        label: this.all_view_shops[i - 1]
                    });
                }
                return data;
            },
//
//            selectedViewShops() {
//                    const that = this;
//                    const data = [];
//                    var viewShopString = that.view_shops + '';
//                    console.log(viewShopString, 'this is view shop string!!!')
//
//                    for(let i = 1; i<= this.viewShopsData.length; i++) {
//                        console.log(this.viewShopsData[i-1].label, '--> this is label')
//                        if(viewShopString.indexOf(this.viewShopsData[i-1].label) >= 0) {
//                            data.push(this.viewShopsData[i-1].key);
//                        }
//                    }
//                    console.log(data, 'this is sisisisisisisiisisissisidata')
//                    return [1,3];
////                ,
////                set: function(newValue) {
////                    const that = this;
////                    const data = [];
////                    var viewShopString = newValue + '';
////                    console.log(viewShopString, 'this is view shop string!!!')
////
////                    for(let i = 1; i<= this.viewShopsData.length; i++) {
////                        if(viewShopString.indexOf(this.viewShopsData[i-1].label) >= 0) {
////                            data.push(this.viewShopsData[i].key);
////                        }
////                    }
////                    console.log(data, 'this is sisisisisisisiisisissisidata')
//////                    return data;
////                    that.selectedViewShops = data;
////                }
//            }
        }
    }
</script>